package com.zjcode.cdcer.service.impl;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.cdcer.mapper.CerPersonalInfoMapper;
import com.zjcode.cdcer.mapper.CerSysteminitImportInfoMapper;
import com.zjcode.cdcer.mapper.ZjcodeSysRegionMapper;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.excel.SysteminitImportInfo;
import com.zjcode.cdcer.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @createTime: 2023-09-27
 * @creater: yong
 */
@Service
public class CerPersonInfoServiceImpl implements CerPersonInfoService , BaseService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CerPersonalInfoMapper cerPersonalInfoMapper;
    @Autowired
    private ZjcodeSysRegionMapper zjcodeSysRegionMapper;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private TkmSysOrgService tkmSysOrgService;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;

    @Override
    public List<CerPersonalInfo> queryAllByLimit(CerPersonalInfo cerPersonalInfo) {
        return cerPersonalInfoMapper.queryAllByLimit(cerPersonalInfo);
    }

    @Override
    public Map<String, Object> listPageData(PageData pageData) {
        String userId = (String) pageData.get("user");

        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());

        List<LinkedHashMap<String,Object>> maps = cerPersonalInfoMapper.listPageData(pageData);

        return PaginationBuilder.buildResult(maps,
                page.getTotal(),
                mPage.getCurrentPage(),
                mPage.getPageSize());
    }

    @Override
    public Map<String, Object> listDataByNameOrIdCard(PageData pageData) {
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        String userId = (String) pageData.get("userId");
        Object name = pageData.get("name");
        // 初始加载，不展示所有；只有当输入姓名或身份证号，才展示数据  -> 改成初始加载选择的绑定村code
//        if (ObjectUtils.isEmpty(name)) {
//            resultMap.put("list", new ArrayList<>());
//            return resultMap;
//        }
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        Object villageCode = pageData.get("villageCode");
        if (ObjectUtils.isNotEmpty(villageCode)) {
            // 用村code值 -> 查机构id
//            // 1、查 机构id 集合
//            List<String> orgIds = cerPersonalInfoMapper.getOrgIdsByNameOrIdCard(pageData);
//            String orgId = tkmSysOrgService.getOrgIdByVillageCode((String)villageCode,orgIds);
//            pageData.put("orgId",orgId);
            pageData.put("villageId",villageCode);
        }
        pageData.put("idCard",name);
        pageData.put("blurFlag",name);
        MPage mPage = getPageInfo(pageData);
        List<LinkedHashMap<String,Object>> maps = cerPersonalInfoMapper.listPageDataNoInitData(pageData);
        resultMap.put("list", maps);
        return resultMap;
    }

    @Override
    public JsonObj getVillagesByNameOrIdCard(PageData pageData) {
        // 参数：name（姓名、身份证号）
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        Object name = pageData.get("name");
        // 初始加载，不展示所有；只有当输入姓名或身份证号，才展示数据 -> 改成初始加载选择的绑定村code列表
//        if (ObjectUtils.isEmpty(name)) {
//            resultMap.put("list", new ArrayList<>());
//            return JsonObj.success(resultMap);
//        }
        String userId = (String) pageData.get("user");
//        String extFlag = sysUserService.findUserExtFlag(userId);
//        pageData.put("extFlag", extFlag);
        String orgId = sysUserService.findOrgByUserId(userId);
        pageData.put("idCard",name);
        pageData.put("blurFlag",name);
        pageData.put("institutionId",orgId);
        // 1、查 机构id 集合
//        List<String> orgIds = cerPersonalInfoMapper.getOrgIdsByNameOrIdCard(pageData);
        List<CityEntity> villages = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(orgIds)) {
            // 2、再查机构关联的村code集合
            List<String> villageCodes = tkmSysOrgService.getVillageCodesByOrgId(orgId);
            // 3、查出村实体的列表
            if (!CollectionUtils.isEmpty(villageCodes)) {
                villages = sequenceService.getVillagesByCodes(villageCodes);
            }
//        }
        resultMap.put("list",villages);
        return JsonObj.success(resultMap);
    }

    @Override
    public int addBatchPersonals(List<CerPersonalInfo> personalInfos) {
        return cerPersonalInfoMapper.addBatchPersonals(personalInfos);
    }

    @Override
    public void checkStreetAndVillage(CerPersonalInfo each) {
        //如果没有对应区级id
        if (StringUtils.isEmpty(each.getDistrictId())) {
//            each.joinErrorMessage("信息需和创建人所在地区一致");
        }else {
            //校验乡镇和村庄
            List<String> ids =new ArrayList<>();
            ids.add(each.getDistrictId());
            //查询区县下面的所有乡镇
            List<LinkedHashMap<String, Object>> allStreets = zjcodeSysRegionMapper.getAllStreets(ids);
            List<LinkedHashMap<String, Object>> streets = allStreets.parallelStream().filter(p -> p.get("title").equals(each.getCountyName())).collect(Collectors.toList());
            if (streets.size()>0){
                //找到了对应的乡镇（街道）
                each.setCountyName(streets.get(0).get("title").toString());
                each.setCountyId(streets.get(0).get("id").toString());
                //查找乡镇下面的所有村庄
                //村庄信息未关联。。。待定
            }else {
                each.joinErrorMessage("请填写正确的乡镇信息");
            }
        }
    }

    @Override
    public int insertRecords(List<CerPersonalInfo> importInfoList) {
        return cerPersonalInfoMapper.insertBatch(importInfoList);
    }

    @Override
    public int updateCerPersonInfo(CerPersonalInfo info) {
        return cerPersonalInfoMapper.update(info);
    }

    @Override
    public int insertCerPersonInfo(CerPersonalInfo info) {
        info.setId(get32UUID());
        return cerPersonalInfoMapper.insert(info);
    }

    @Override
    public CerPersonalInfo getPersonInfoById(String id) {
        return cerPersonalInfoMapper.queryById(id);
    }

    @Override
    public CerPersonalInfo getPersonInfoByIdCard(String idCard) {
        return cerPersonalInfoMapper.getPersonInfoByIdCard(idCard);
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryAllExportDataBy(PageData pageData) {
        String userId = (String) pageData.get("user");
        String ids = (String) pageData.get("ids");
        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);
        // 查询数据自定并分组
//        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
//        Map<String, List<SysDict>> keyListMap = allCerDicts
//                .stream()
//                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 获取ids
        List<String> idList = new ArrayList<>();
        if (!StringUtils.isEmpty(ids)) {
            idList.addAll(Arrays.asList(ids.split("\\|")));
        }

        List<LinkedHashMap<String, Object>> list = cerPersonalInfoMapper.selectAllByExtFlagAndIdList(
                ids,
                idList,pageData);
        return  list;

    }

    @Override
    public int getCountByIdCardAndInstitutionId(String orgId, String idCard) {
        return cerPersonalInfoMapper.getCountByIdCardAndInstitutionId(orgId,idCard);
    }

    @Override
    public JsonObj delPersonInfo(String id) {
        Integer count = cerPersonalInfoMapper.selByPersonId(id);
        if (count > 0) {
            return JsonObj.error("当前数据已进行上报");
        }
        Integer i = cerPersonalInfoMapper.delPersonInfo(id);
        if (i > 0) {
            return JsonObj.success("删除成功");
        } else {
            return JsonObj.error("删除失败");
        }
    }


}
